package com.xh.core.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/*
 * @Author daiwei
 * @Description
 * @Date 2020/2/13 22:58
 **/
public class ExecUtils {

    /**
     * 执行命令
     * @param cmd
     * @return
     */
    public static String exec(List<String> cmd){
        ProcessBuilder builder = new ProcessBuilder();
        Process process = null;
        try {
            builder.command(cmd);
            process=builder.start();
        } catch (Exception e) {
            e.printStackTrace();
            return "execOpError";
        }
        StringBuilder msg=new StringBuilder();

        try {
            // 使用这种方式会在瞬间大量消耗CPU和内存等系统资源，所以这里我们需要对流进行处理
            InputStream errorStream = process.getErrorStream();
            InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
            BufferedReader br = new BufferedReader(inputStreamReader);

            String line = "";
            while ((line = br.readLine()) != null) {
                msg.append(line);
            }
            if (br != null) {
                br.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (errorStream != null) {
                errorStream.close();
            }
        }catch (Exception ex){
            return "error";
        }finally {
        }
        return msg.toString();
    }
}
